<?php
// API接口文件，用于处理与AI API的交互

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

session_start();

// 检查是否已安装
$install_file = './data/installed.txt';
if (!file_exists($install_file)) {
    echo json_encode(['error' => '系统未安装，请先完成安装']);
    exit;
}

// 加载配置
if (!file_exists('./data/config.php')) {
    echo json_encode(['error' => '配置文件不存在']);
    exit;
}
require_once './data/config.php';

// 数据库连接
try {
    $pdo = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo json_encode(['error' => '数据库连接失败: ' . $e->getMessage()]);
    exit;
}

// 获取用户IP
function getUserIP() {
    $ip_keys = ['HTTP_X_FORWARDED_FOR', 'HTTP_X_REAL_IP', 'HTTP_CLIENT_IP', 'REMOTE_ADDR'];
    foreach ($ip_keys as $key) {
        if (!empty($_SERVER[$key])) {
            $ip = $_SERVER[$key];
            if (strpos($ip, ',') !== false) {
                $ip = trim(explode(',', $ip)[0]);
            }
            if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
                return $ip;
            }
        }
    }
    return $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
}

// 获取POST数据
$input = json_decode(file_get_contents('php://input'), true);

if (!$input || !isset($input['message'])) {
    echo json_encode(['error' => '无效的请求数据']);
    exit;
}

$user_message = trim($input['message']);
$user_ip = getUserIP();

// 获取聊天历史
$stmt = $pdo->prepare("SELECT message, response FROM chat_history WHERE user_ip = ? ORDER BY timestamp ASC LIMIT 20");
$stmt->execute([$user_ip]);
$chat_history = $stmt->fetchAll(PDO::FETCH_ASSOC);

// 准备消息历史
$messages = [
    ['role' => 'system', 'content' => 'You are a helpful assistant.']
];

// 添加历史记录（限制最近的对话）
foreach ($chat_history as $chat) {
    $messages[] = ['role' => 'user', 'content' => $chat['message']];
    $messages[] = ['role' => 'assistant', 'content' => $chat['response']];
}

// 添加当前消息
$messages[] = ['role' => 'user', 'content' => $user_message];

$curl = curl_init();

curl_setopt_array($curl, [
    CURLOPT_URL => $base_url . "/chat/completions",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => json_encode([
        'model' => $default_model,
        'messages' => $messages,
        'temperature' => 0.7,
        'max_tokens' => 1000
    ]),
    CURLOPT_HTTPHEADER => [
        "Content-Type: application/json",
        "Authorization: Bearer $api_key"
    ],
    CURLOPT_TIMEOUT => 60
]);

$response = curl_exec($curl);
$http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);

if ($http_code === 200) {
    $data = json_decode($response, true);
    if (isset($data['choices'][0]['message']['content'])) {
        $ai_response = trim($data['choices'][0]['message']['content']);
        
        // 保存到数据库
        $stmt = $pdo->prepare("INSERT INTO chat_history (user_ip, message, response) VALUES (?, ?, ?)");
        $stmt->execute([$user_ip, $user_message, $ai_response]);
        
        echo json_encode([
            'success' => true,
            'response' => $ai_response
        ]);
    } else {
        echo json_encode(['error' => 'API响应格式不正确']);
    }
} else {
    echo json_encode([
        'error' => 'API请求失败',
        'details' => "HTTP状态码: $http_code",
        'response' => $response
    ]);
}
